Classes java.util.Random and java.util.SplittableRandom didn't used to have a common ancestor, making it difficult to write methods that take either. This was finally fixed in Java 17. Let's have a look at some random Java topics together. Full Article
A few years ago, the second oldest man in our village Chorafakia wrote a book about the history of our area. Only catch - it was in Cretan Greek. I tried to read it, but couldn't. Google Translate shrugged at the strange Cretan dialect. Then ChatGPT 4.0 came along, and we can interact with it dir... Full Article
The printf() method in Java borrows heavily from C, including the alternate flag #. But %s works a bit differently in Java. In this newsletter we explore this a bit more deeply. Full Article
We can construct our TreeSet with our own Comparator, however, we need to be careful that it conforms to the specification. The Comparator needs to be consistent with equals() and hashCode() of the elements, otherwise we might end up with a TreeSet with non-symmetric equals() behaviour. Full Article
Javadoc specifies the details of our methods using special tags such as @param and @return. After Java 5, we did not see new standard Javadoc tags for 13 years. The hope was that annotations would replace the chaos of doclets. But tags have not disappeared. In this newsletter, we examine several ... Full Article
Reflection returns the modifiers of class elements as an unqualified int bitset. Unfortunately some of the bits have a different meaning depending on their context. For example, a method can have their transient bit set, even though that does not make sense for a method. In Java 20, we now have a... Full Article
JEP 290 introduced the ObjectInputFilter, which we can use to filter objects returned from an ObjectInputStream. We examine three ways of making filters, through subclassing, with factory methods and with text patterns, and then show some interesting edge cases. Full Article
Some Map implementations allow null keys and values. This leads to funky behaviour when calling putIfAbsent() and the compute functions. In this newsletter we look a bit more closely at the issues at hand when allowing nulls in maps. Full Article
"Would you like to play with me?" - Summer holidays are a good time to relax and whip out a board game or two. In this newsletter we explore a children's favourite - snakes and ladders, with a simulation written in Java. Full Article
If we have a List
Java 8 Streams were the first time that Java deliberately split utility classes into multiple versions to be used for Object, int, long and double. This design was also applied to Iterator, which now has specialized types for these primites in the form of the PrimitiveIterator. In this newsletter... Full Article
A nice puzzle to brighten your day - how can we make the Iterator think that the List has not been changed? Full Article
Java 14 Records (JEP359) reduce the boiler plate for simple POJOs. In this newsletter we look at what special magic is used to serialize and deserialize these new records. Full Article
In our previous newsletter we enhanced Java 8 Streams by decorating them with an EnhancedStream class. The code had a lot of repetition, which often leads to bugs if written by hand. In this newsletter we use a dynamic proxy to create an EnhancedStream. The resulting code is shorter and more c... Full Article
Java 8 Streams have a rather narrow-minded view of what makes objects distinct. In this newsletter, we enhance Streams to allow a more flexible approach for deciding uniqueness. Full Article
Class.getMethods() returns all the public methods in this class and the classes in its ancestry. However, we cannot necessarily call these methods, for example if they are declared in a private inner class or a lambda. In this newsletter we attempt to find all truly public methods. Full Article
In a previous newsletter, we looked at how we could dynamically add new enums and also rewire affected switch statements. Due to improvements in Java security, our old approach needs to be updated for Java 12. Full Article
The compareTo() function has three rules. Break any one of them and you might get an exception when you sort. In this newsletter we explore what these rules are and how they can affect sorting. Full Article
In today's puzzle, we want to sort a list of persons. It works in some versions of Java, but not in others. You need to figure out why. Full Article
Anonymous inner classes can be used effectively in Java 8 Streams to create tuples. See how this can improve our refactoring of old procedural code into the functional paradigm. Full Article
A well known exploit with maps is to create a lot of Strings as keys that all have the same hash code. In this newsletter we see how easily that can be done and what Java 8+ HashMap does to protect itself. Full Article
Sorting a stream is easy. But what if we want the opposite: shuffling? We can shuffle a List with Collections.shuffle(List). But how can we apply that to a Stream? In this newsletter we show how with Collectors.collectingAndThen(). Full Article
We now look at why the best-case scenario for a getMethod() call is O(n), not O(1) as we would expect. We also discover that the throughput of getMethod() has doubled in Java 9. Full Article
What is the best-case computational time complexity for finding a method inside a class via reflection? In this newsletter we do not answer that question. Instead, we look at the GoF Builder and wonder whether anyone has ever used it in Java. Full Article
We build a simple custom Spliterator to allow us to stream over dates to find how many times the 1st of January was on a Monday. Full Article
Java 9 now offers immutable lists, sets and maps. We look at how to create them and also how to do simple set operations like union and intersection. Full Article
The LinkedHashMap has an interesting feature, where we can order elements in "access order", rather than the default "insertion order". This allows us to build a light-weight LRU cache. Full Article
For our 16th anniversary edition, we have produced three short video tutorials on how to build your own CircularArrayList in Java, based on the AbstractList. Full Article
We humans are rather good at figuring out what is meant from context. Computers are terrible. They do exactly what we tell them to. Fun ensues when we feed them wrong number formatting information. Full Article
List has a new method sort(Comparator). This is handy, as it allows implementations to specialize how to sort their internal data structures. Vector only synchronizes once per list, not once per element. ArrayList avoids copying the array unnecessarily. CopyOnWriteArrayList works. Full Article
Java 7 quietly changed the structure of String. Instead of an offset and a count, the String now only contained a char[]. This had some harmful effects for those expecting substring() would always share the underlying char[]. Full Article
ThreadLocals should in most cases be avoided. They can solve some tough problems, but can introduce some nasty memory leaks, especially if the ThreadLocal class or value refer to our own classes, not a system class. In this newsletter we show some mechanisms that help under OpenJDK. Full Article
ExecutorService allows us to submit either Callable or Runnable. Internally, this is converted to a FutureTask, without the possibility of extracting the original task. In this newsletter we look at how we can dig out the information using reflection. Full Article
How can you discover all the places in your program where threads are being constructed? In this newsletter we create our own little SecurityManager to keep an eye on thread creation. Full Article
The LinkedHashMap has a little known feature that can return elements in least recently accessed order, rather than insertion order. In this newsletter we use this to construct a "Recently Used File" list. Full Article
We continue our discussion on Unicode by looking at how we can compare text that uses diacritical marks or special characters such as the German Umlaut. Full Article
Unicode is the most important computing industry standard for representation and handling of text, no matter which of the world's writing systems is used. This newsletter discusses some selected features of Unicode, and how they might be dealt with in Java. Full Article
Rule Based Programming, a declarative programming paradigm, is based on logical patterns to select data and associate it with processing instructions. This is a more indirect method than the sequential execution steps of an imperative programming language. Full Article
It is almost Christmas time, which gives us an excuse to invest in all sorts of toys. I found that the most ridiculously priced ones are those that promise to have an added benefit besides fun. "Educational", "Good for hand-eye coordination", etc. In this Java newsletter we look at one of thes... Full Article
We look at how we could internalize the iteration into a collection by introducing a Processor interface that is applied to each element. This allows us to manage concurrency from within the collection. Full Article
Concurrency is easier when we work with immutable objects. In this newsletter, we define another concurrency law, The Law of the Xerox Copier, which explains how we can work with immutable objects by returning copies from methods that would ordinarily modify the state. Full Article
De-Serialization creates objects without calling constructors. We can use the same mechanism to create objects at will, without ever calling their constructors. Full Article
The DateFormat produces some seemingly unpredictable results parsing the date 2009-01-28-09:11:12 as "Sun Nov 30 22:07:51 CET 2008". In this newsletter we examine why and also show how DateFormat reacts to concurrent access. Full Article
One of the hardest exceptions to get rid of in a system is th ConcurrentModificationException, which typically occurs when a thread modifies a collection whilst another is busy iterating. In this newsletter we show how we can fail on the modifying, rather than the iterating thread. Full Article
Java's serialization mechanism is optimized for immutable objects. Writing objects without resetting the stream causes a memory leak. Writing a changed object twice results in only the first state being written. However, resetting the stream also loses the optimization stored in the stream. Full Article
Timers in Java have suffered from the typical Command Pattern characteristics. Exceptions could stop the timer altogether and even with the new ScheduledPoolExecutor, a task that fails is cancelled. In this newsletter we explore how we could reschedule periodic tasks automatically. Full Article
In this newsletter, we look at how we can read from the console input stream, timing out if we do not get a response by some timeout. Full Article
Mustang introduced a ServiceLoader than can be used to load JDBC drivers (amongst others) simply by including a jar file in your classpath. In this newsletter, we look at how we can use this mechanism to define and load our own services. Full Article
A common idiom for logging is to create a logger in each class that is based on the class name. The name of the class is then duplicated in the class, both in the class definition and in the logger field definition, since the class is for some reason not available from a static context. Read ho... Full Article
In this newsletter, we look at a technique of how we can replace an existing database driver with our own one. This could be used to migrate an application to a new database where you only have the compiled classes. Or it could be used to insert a monitoring JDBC connection that measures the le... Full Article
Sometimes it is useful to have a look at what the threads are doing in a light weight fashion in order to discover tricky bugs and bottlenecks. Ideally this should not disturb the performance of the running system. In addition, it should be universally usable and cost nothing. Have a look at h... Full Article
In this newsletter, we show how simple it is to send emails from Java. This should obviously not be used for sending unsolicited emails, but will nevertheless illustrate why we are flooded with SPAM. Full Article
In this Java Specialists' Newsletter, we look at a simple Java program that solves SuDoKu puzzles. Full Article
Sometimes you need to download files using HTTP from a machine that you cannot run a browser on. In this simple Java program we show you how this is done. We include information of your progress for those who are impatient, and look at how the volatile keyword can be used. Full Article
A simple database viewer written in Java Swing that reads the metadata and shows you all the tables and contents of the tables, written in under 100 lines of Java code, including comments. Full Article
Don't Repeat Yourself. The mantra of the good Java programmer. But database code often leads to this antipattern. Here is a neat simple solution from the Jakarta Commons DbUtils project. Full Article
Follow-up to show another approach that works even better for initializing fields prior to the call to super(). Full Article
We cannot execute any code before calling the superclass constructor. Or can we? Read more to find out. Full Article
Get: every new article, exclusive invites to live webinars, our top-10 articles ever, access to expert tutorials & more!
Java Champion, author of the Javaspecialists Newsletter, conference speaking regular... About Heinz
We deliver relevant courses, by top Java developers to produce more resourceful and efficient programmers within their organisations.
We can help make your Java application run faster and trouble-shoot concurrency and performance bugs...
We deliver relevant courses, by top Java developers to produce more resourceful and efficient programmers within their organisations. Find Out More